package com.sxp.servlet;

import com.sxp.bean.User;
import com.sxp.dao.UserDao;
import com.sxp.dao.impl.UserDaoImpl;
import com.sxp.util.EncryptUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author hsowan
 * @date 2019-06-13
 **/
@WebServlet("/password")
public class UpdatePasswordServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oldPassword = req.getParameter("oldpassword");
        String newpassword = req.getParameter("newpassword");
        String repassword = req.getParameter("repassword");

        HttpSession session = req.getSession();

        if (oldPassword != null && newpassword != null && repassword != null) {
            if (newpassword.equals(repassword)) {

                User user = (User) session.getAttribute("user");
                if (user == null) {
                    session.setAttribute("msg", "未登录！");
                    resp.sendRedirect("/obs/message.jsp");
                }else {
                    if (user.getPassword().equals(EncryptUtils.md5(oldPassword))) {
                        user.setPassword(EncryptUtils.md5(newpassword));
                        UserDao userDao = new UserDaoImpl();
                        userDao.update(user);
                        session.setAttribute("msg", "修改成功");
                        resp.sendRedirect("/obs/message.jsp");
                    } else {
                        session.setAttribute("msg", "旧密码不正确！");
                        resp.sendRedirect("/obs/message.jsp");
                    }
                }
            } else {
                session.setAttribute("msg", "两次新密码不一样！");
                resp.sendRedirect("/obs/message.jsp");
            }

        } else {
            session.setAttribute("msg", "输入不能有空！");
            resp.sendRedirect("/obs/message.jsp");
        }



    }
}
